package kvm

import (
	"github.com/rs/zerolog/log"
	"github.com/sourcegraph/conc"
)

const (
	kvmDomain      = "http://idc-kvm.alauda.cn:19999"
	pathOfAdd      = "/api/vmoper/addip"
	pathOfStatus   = "/api/vmoper/status"
	pathOfStart    = "/api/vmoper/start"
	pathOfShutdown = "/api/vmoper/shutdown"
	pathOfDestroy  = "/api/vmoper/destroy"
)

type Kvm struct {
	Nodes []*Node
}

func NewKvm(Nodes []*Node) *Kvm {
	k := &Kvm{Nodes: Nodes}
	k.AddToWhiteList()
	return k
}

func (k *Kvm) RefreshStatus() {
	var wg conc.WaitGroup
	for _, node := range k.Nodes {
		node := node
		wg.Go(func() {
			node.Status = node.GetStatus()
		})
	}
	wg.Wait()
}

func (k *Kvm) AddToWhiteList() {
	var wg conc.WaitGroup
	for _, node := range k.Nodes {
		node := node
		wg.Go(func() {
			err := node.AddToWhiteList()
			if err != nil {
				log.Err(err).Send()
			}
		})
	}
	wg.Wait()
}

func (k *Kvm) Start() {
	var wg conc.WaitGroup
	for _, node := range k.Nodes {
		node := node
		wg.Go(func() {
			err := node.Start()
			if err != nil {
				log.Err(err).Send()
			}
		})
	}
	wg.Wait()
}

func (k *Kvm) Stop(force bool) {
	var wg conc.WaitGroup
	for _, node := range k.Nodes {
		node := node
		wg.Go(func() {
			err := node.Stop(force)
			if err != nil {
				log.Err(err).Send()
			}
		})
	}
	wg.Wait()
}
